<?php namespace App\Foundation\Common;

use App\Repositories\Eloquent\User\Entity\SocialiteUser;

/**
 * @property int $device_type         设备类型 : 1.android, 2.ios, 3.其他
 *
 * Class Client
 *
 * @package App\Foundation\Common
 */
class Client
{
    /**
     * User agent of client.
     *
     * @var string
     */
    public $user_agent;

    /**
     * 用户ip
     *
     * @var string
     */
    public $ip;

    /**
     * 邀请人uid
     *
     * @var int
     */
    public $invite_uid;

    /**
     * 获取终端设备类型
     *
     * @return int
     */
    public function getDeviceTypeAttribute()
    {
        $this->device_type = SocialiteUser::DEVICE_TYPE_OTHER;
        if (preg_match('/\(i[^;]+;( U;)? CPU.+Mac OS X/', $this->user_agent)) {
            $this->device_type = SocialiteUser::DEVICE_TYPE_IOS;
        } elseif (preg_match('/Android|Linux/', $this->user_agent)) {
            $this->device_type = SocialiteUser::DEVICE_TYPE_ANDROID;
        }

        return $this->device_type;
    }

    /**
     * 设置用户端的UA
     *
     * @param $user_agent
     */
    public function setUserAgent($user_agent)
    {
        $this->user_agent = $user_agent;
    }

    /**
     * 设置用户ip
     *
     * @param $ip
     */
    public function setIp($ip)
    {
        $this->ip = $ip;
    }

    /**
     * 邀请人uid
     *
     * @param $invite_uid
     */
    public function setInviteUid($invite_uid)
    {
        $this->invite_uid = (int)$invite_uid;
    }

    /**
     * Handle dynamic method calls into the client.
     *
     * @param $name
     * @param $parameters
     *
     * @return mixed
     * @throws \Exception
     */
    public function __get($name)
    {
        if (isset($this->{$name})) {
            return $this->{$name};
        }

        $method = 'get' . studly_case($name) . 'Attribute';
        if (method_exists($this, $method)) {
            return $this->$method();
        }

        throw new \Exception(__CLASS__ . ' undefined ' . $name . ' property.');
    }

}
